package com.sina.shop.manage.dao.carousel;

import com.sina.shop.dao.ShopDataSourceDao;
import com.sina.shop.domain.carousel.Carousel;
import com.sina.shop.domain.carousel.Carousel_;
import com.sina.shop.domain.Status;
import com.sina.shop.util.FileSizeChangeUtil;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.TupleElement;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2017-11-23-14:24
 */
@Repository("carouselManageDao")
public class CarouselManageDaoImpl extends ShopDataSourceDao implements CarouselManageDao {

    @Override
    public int deleteCarousel(Long id) {
        return template.executeWithNativeSession(session -> {
            String hql = "delete from Carousel c where c.id = :id";
            Query query = session.createQuery(hql);
            query.setParameter("id", id);

            return query.executeUpdate();
        });
    }

    @Override
    public int deleteCarouselTab(Long id) {
        return template.executeWithNativeSession(session -> {
            String hql = "update Carousel c set c.status=:status where c.id = :id";
            Query query = session.createQuery(hql);
            query.setParameter("id", id);
            query.setParameter("status", Status.NOT_USE);
            return query.executeUpdate();
        });
    }

    @Override
    public List<Map<String, Object>> getCarouselList(Carousel carousel) {
        return template.executeWithNativeSession(session -> {
            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            //所要查询的实体
            Root<Carousel> root = criteriaQuery.from(Carousel.class);
            //指定要在查询结果中返回的选择项
            criteriaQuery.multiselect(
                    carouselSelection(root)
            );

            Predicate predicate = carouselPredicate(carousel, builder, root);
            //指定查询条件
            criteriaQuery.where(predicate);
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.desc(root.get(Carousel_.id))
            );
            //创建查询
            Query<Tuple> query = session.createQuery(criteriaQuery);
            //得到起始条数
            int first = (carousel.getPage() - 1) * carousel.getRows();

            query.setFirstResult(first);
            query.setMaxResults(carousel.getRows());
            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class, true);
        });
    }

    @Override
    public Long getCarouselCount(Carousel carousel) {
        return template.executeWithNativeSession(session -> {

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
            Root<Carousel> root = criteriaQuery.from(Carousel.class);
            //根据id查找结果数
            criteriaQuery.select(
                    builder.count(root.get(Carousel_.id))
            );
            //组装查询条件
            criteriaQuery.where(
                    carouselPredicate(carousel, builder, root)
            );
            //创建插叙语句
            Query<Long> query = session.createQuery(criteriaQuery);
            long count;
            try {
                //得到结果条数
                count = query.getSingleResult();
            } catch (NoResultException e) {
                count = 0;
            }
            return count;
        });
    }

    /**
     * 查询条件组装类
     *
     * @param carousel
     * @param builder
     * @param root
     * @return
     */
    protected Predicate carouselPredicate(Carousel carousel, CriteriaBuilder builder
            , Root<Carousel> root) {
        List<Predicate> list = new ArrayList<>(4);

        if (carousel.getLastId() != null) {
            list.add(
                    builder.lt(root.get(Carousel_.id), carousel.getLastId())
            );
        }

        if (carousel.getName() != null) {
            list.add(
                    builder.like(root.get(Carousel_.name), "%" + carousel.getName() + "%")
            );
        }

        if (carousel.getCreateStart() != null) {
            list.add(
                    builder.greaterThanOrEqualTo(root.get(Carousel_.localDateTime), carousel.getCreateStart())
            );
        }

        if (carousel.getCreateEnd() != null) {
            list.add(
                    builder.lessThanOrEqualTo(root.get(Carousel_.localDateTime), carousel.getCreateEnd())
            );
        }
        //if (documents.getStatus() != null) {
        list.add(
                builder.equal(root.get(Carousel_.status), Status.USE)
        );
        //}

        return builder.and(
                list.toArray(new Predicate[list.size()])
        );
    }


    /**
     * 所要查询的字段组装类
     *
     * @param root
     * @return
     */
    protected List<Selection<?>> carouselSelection(Root<Carousel> root) {

        List<Selection<?>> list = new ArrayList<>(12);
        /**
         * 五条一组
         */
        list.add(root.get(Carousel_.id).as(Long.class).alias("id"));//id
        list.add(root.get(Carousel_.originalFileName).alias("originalFileName"));//
        list.add(root.get(Carousel_.storageFileName).alias("storageFileName"));
        list.add(root.get(Carousel_.cloudStorageAddress).alias("cloudStorageAddress"));
        list.add(root.get(Carousel_.fileSize).alias("fileSize"));

        list.add(root.get(Carousel_.name).alias("name"));//
        list.add(root.get(Carousel_.status).alias("status"));//
        list.add(root.get(Carousel_.localDateTime).alias("localDateTime"));


        return list;
    }


    protected final List<Map<String, Object>> mapWrapperFromTuple(List<Tuple> tupleList, Class<?> mapClass, Boolean isSizePrint) {

        if (!Map.class.isAssignableFrom(mapClass)) {
            throw new RuntimeException(String.format("mapClass[%s] is assignable from", mapClass));
        }

        List<Map<String, Object>> list = new ArrayList<>(tupleList.size());

        Map<String, Object> map;

        for (Tuple tuple : tupleList) {
            map = wrapperToMapFromTuple(tuple, mapClass, isSizePrint);
            list.add(map);
        }
        return list;
    }

    protected final Map<String, Object> wrapperToMapFromTuple(Tuple tuple, Class<?> mapClass, Boolean isSizePrint) {
        Map<String, Object> map;

        List<TupleElement<?>> elementList = tuple.getElements();

        map = createMap((int) (elementList.size() / 0.75f), mapClass);

        for (TupleElement<?> e : elementList) {
            if (e.getAlias().equals("fileSize")) {
                map.put(e.getAlias(), FileSizeChangeUtil.getPrintSize(Long.parseLong(tuple.get(e).toString())));
            } else {
                map.put(e.getAlias(), tuple.get(e));
            }
        }

        return map;
    }
}
